package org.dromara.common.wechat.pay.config

import com.wechat.pay.java.core.RSAPublicKeyConfig
import org.dromara.common.wechat.pay.config.properties.WechatPayProperties
import org.dromara.common.wechat.pay.service.WechatPayService
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.core.io.DefaultResourceLoader
import org.springframework.util.StreamUtils

@AutoConfiguration
@ConditionalOnProperty(value = ["wechat.pay.enabled"], havingValue = "true")
@EnableConfigurationProperties(WechatPayProperties::class)
class WechatPayConfig {

    val privateKey by lazy {
        val inputStream = DefaultResourceLoader().getResource("wechat_pay/apiclient_key.pem").inputStream
        val privateKey = StreamUtils.copyToString(inputStream, Charsets.UTF_8)
        inputStream.close()
        privateKey
    }

    val publicKey by lazy {
        val inputStream = DefaultResourceLoader().getResource("wechat_pay/pub_key.pem").inputStream
        val publicKey = StreamUtils.copyToString(inputStream, Charsets.UTF_8)
        inputStream.close()
        publicKey
    }

    @Bean
    fun wechatPayConfig(wechatPayProperties: WechatPayProperties): RSAPublicKeyConfig {
        return RSAPublicKeyConfig.Builder()
            .merchantId(wechatPayProperties.merchantId)
            .merchantSerialNumber(wechatPayProperties.merchantSerialNumber)
            .apiV3Key(wechatPayProperties.apiV3Key)
            .publicKeyId(wechatPayProperties.publicKeyId)
            .privateKey(privateKey)
            .publicKey(publicKey)
            .build()
    }

    @Bean
    fun wechatPayService(
        wechatPayConfig: RSAPublicKeyConfig,
        wechatPayProperties: WechatPayProperties
    ): WechatPayService {
        return WechatPayService(wechatPayConfig, wechatPayProperties)
    }
}
